<template>
  <div>
    <el-dialog
      :title="{ add: '新增角色', edit: '编辑角色' }[mode]"
      :visible="show"
      @close="closePopout"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="角色名称" label-width="80px" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px" prop="description">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePopout">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setting'

export default {
  props: ['show'],

  data() {
    return {
      form: {
        name: '', // string	必须		角色名称
        description: '' // string	必须		角色描述
      },
      // 表单验证
      rules: {
        name: [
          { required: true, message: '此项为必填项目', trigger: 'change' },
          {
            min: 1,
            max: 50,
            message: '请输入正确的角色名称',
            trigger: 'change'
          }
        ],
        description: [
          { required: true, message: '此项为必填项目', trigger: 'change' },
          {
            min: 1,
            max: 50,
            message: '请输入正确的角色描述',
            trigger: 'change'
          }
        ]
      },
      // 区分点击的按钮就
      mode: 'add'
    }
  },

  methods: {
    // 关闭弹框
    closePopout() {
      this.$emit('update:show', false)
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 新增角色
    addRole() {
      this.$refs.form.validate(async(result) => {
        // result:true:验证通过，false:验证失败
        if (result) {
          if (this.mode === 'add') {
            await sysRolePost(this.form)
            this.$message.success('新增成功')
          } else if (this.mode === 'edit') {
            await sysRolePut(this.form)
            this.$message.success('编辑成功')
          }
          this.closePopout()
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style></style>
